package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FocusUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FocusUserApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private FocusUserApi focusUserApi;

    @CacheEvict(value = "videoList",allEntries = true) //清除缓存
    public ResponseEntity uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {

        Video video = new Video();
        video.setUserId(UserHolder.getUserId());

//        封面图片上传到阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        video.setPicUrl(picUrl);

//        小视频上传到FASTDFS
        //        InputStream inputStream, long fileSize, String fileExtName, Set< MetaData > metaDataSet null
//        获取扩展名 截取  从最后一个点出现的位置
        String fileName = videoFile.getOriginalFilename();
        String extName = fileName.substring(fileName.lastIndexOf(".")+1);
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream() , videoFile.getSize(), extName, null);

        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
        video.setVideoUrl(videoUrl);
        video.setText("class158发布的小视频");

        videoApi.save(video);

        return ResponseEntity.ok(null);

    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Cacheable(value = "videoList",key = "#page+'_'+#pagesize")
    public PageResult queryVideo(Integer page, Integer pagesize) {
//        查mongo    按理说这里应该查询推荐的小视频recommend_video  但是为了给大家讲一个缓存的技术 这里就直接查询Video
      PageResult pageResult = videoApi.queryVideoList(page,pagesize);
      List<Video> videoList = (List<Video>) pageResult.getItems();


      List<VideoVo> list = new ArrayList<>();
//        查mysql
        for (Video video : videoList) {
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            if(userInfo==null){
                continue;
            }
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getId().toString());
            videoVo.setUserId(userInfo.getId());
            videoVo.setAvatar(userInfo.getAvatar());
            videoVo.setNickname(userInfo.getNickname());
            videoVo.setCover(video.getPicUrl()); //小视频封面
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setSignature(video.getText());
            videoVo.setLikeCount(video.getLikeCount());
//            videoVo.setHasLiked();  //当前登录人是否对这个小视频点赞 TODO
//            videoVo.setHasFocus();  //当前登录人是否关注了这个视频博主 TODO
//            redisTemplate.delete("vidoe_focus_"+UserHolder.getUserId()+"_"+focusUserId);
            if(redisTemplate.hasKey("vidoe_focus_"+UserHolder.getUserId()+"_"+video.getUserId())){
                videoVo.setHasFocus(1);
            }else{
                videoVo.setHasFocus(0);
            }


            videoVo.setCommentCount(video.getCommentCount());

            list.add(videoVo);
        }
        pageResult.setItems(list);
        System.out.println("进入到了queryVideoList方法，代表进入数据了查询");
//                Video  UserInfo --->VideoVo

        return pageResult;

    }
    @CacheEvict(value = "videoList",allEntries = true) //清除缓存
    public ResponseEntity userFocus(Long focusUserId) {
//        xxxApi.save(focusUser);
        focusUserApi.save(UserHolder.getUserId(),focusUserId);

        redisTemplate.boundValueOps("vidoe_focus_"+UserHolder.getUserId()+"_"+focusUserId).set("");
        return ResponseEntity.ok(null);
    }
    @CacheEvict(value = "videoList",allEntries = true) //清除缓存
    public ResponseEntity userUnFocus(Long focusUserId) {
        focusUserApi.delete(UserHolder.getUserId(),focusUserId);
        redisTemplate.delete("vidoe_focus_"+UserHolder.getUserId()+"_"+focusUserId);
        return ResponseEntity.ok(null);
    }
}
